#!/usr/bin/env bash
########################
export PULSE_SERVER=127.0.0.1
#The default pulseaudio server address is 127.0.0.1
#本机默认音频服务地址为127.0.0.1,默认端口为4713。
#Die Standard-Audiodienst Adresse dieses Geräts lautet 127.0.0.1

VNC_RESOLUTION=1440x720
#The default resolution is 1440x720, it is recommended that you adjust it according to the screen ratio.
#默认分辨率为1440x720,您可以修改为其他值,例如3840x2160,2880x1440,2400x1200,1920x1080,1920x960,720x1140,1280x1024,1280x960,1280x720,1024x768,800x680等等。
#Die Standardauflösung ist 1440x720

TMOE_VNC_DISPLAY_NUMBER=2
#If the display number=2,then vnc port=5902.
#若显示编号为2,则vnc端口为$((5900+2))=5902。
#Wenn die Anzeigenummer 2 ist, ist der vnc-Port 5902

VNC_USER=$(whoami)
#You can specify a VNC user. Default is current user: "$(whoami)"
#您可以指定VNC用户，例如root或ubuntu，默认为$(whoami)
#Sie können einen VNC-Benutzer angeben

VNC_LOCALHOST=false
#Only allow connections from localhost.Default is false.
#当此变量的值为true时，仅允许本机连接；为false时，允许局域网连接。默认为false
#Wenn dieser Parameterwert "true" ist, lassen Sie nur Verbindungen von localhost zu

VNC_SERVER=tiger
#You can choose tiger or tight.
#服务端可选tiger或tight。
#Sie können "tiger" oder "tight" wählen.

ZLIB_LEVEL=0
#Zlib  compression  level  for  ZRLE encoding (it does not affect Tight encoding).Acceptable values are between 0  and  9.
#压缩级别,可选0至9,默认为0。
#Die Standardkomprimierungsstufe für zlib ist 0

PIXEL_DEPTH=24
#Specify the pixel depth in bits of the desktop to be created. Default is 24.
#色彩/位/像素深度，可选16、24或32,默认为24，建议选用16或者24。
#Die Standardpixeltiefe beträgt 24

ALWAYS_SHARED=true
#Always treat incoming connections as shared, regardless of the client-specified setting.Default is true.

DBUS_ENABLED=true
####################
if [[ ${VNC_USER} != $(whoami) && -n ${VNC_USER} ]]; then
    if grep -q "^${VNC_USER}:" /etc/passwd; then
        CURRENT_HOME=$(grep "^${VNC_USER}:" /etc/passwd | awk -F ':' '{print $6}' | head -n 1)
        HOME=${CURRENT_HOME}
    else
        printf "\033[33m%s\033[m %s \033[32m%s \033[m%s\n" "WARNING！" "You should type" "useradd -m ${VNC_USER}" "to creat it."
        unset VNC_USER
    fi
    #sudo su - ${VNC_USER} -c "startvnc" || su - ${VNC_USER} -c "startvnc"
    #return 0
fi
###################
X509_VNC_ENABLED=false
#Default is false.
X509_KEY=${HOME}/.vnc/x509-key.pem
#Path to the key of the X509 certificate in PEM format
X509_CERTIFICATE=${HOME}/.vnc/x509-cert.pem
#Path to the X509 certificate in PEM format
####################
RED=$(printf '\033[31m')
PURPLE=$(printf '\033[0;35m')
GREEN=$(printf '\033[32m')
YELLOW=$(printf '\033[33m')
BLUE=$(printf '\033[34m')
BOLD=$(printf '\033[1m')
RESET=$(printf '\033[m')
printf "${GREEN}%s ${YELLOW}%s${RESET} %s\n" "Starting" "vnc server" "..."
printf "%s\n" "Current ${BLUE}vnc port${RESET} is ${YELLOW}$((${TMOE_VNC_DISPLAY_NUMBER} + 5900))${RESET},and vnc address is ${GREEN}localhost${YELLOW}:$((${TMOE_VNC_DISPLAY_NUMBER} + 5900))${RESET}"
export USER=${VNC_USER}
stopvnc -non-stop-dbus 2>/dev/null
TMOE_LINUX_DIR='/usr/local/etc/tmoe-linux'
TMOE_GIT_DIR="${TMOE_LINUX_DIR}/git"
TMOE_TOOL_DIR="${TMOE_GIT_DIR}/tools"
TMOE_VNC_PASSWD_FILE="${HOME}/.vnc/passwd"
XSESSION_FILE='/etc/X11/xinit/Xsession'
TMOE_LOCALE_FILE="${TMOE_LINUX_DIR}/locale.txt"
TIGERVNC_CONFIG_FILE='/etc/tigervnc/vncserver-config-tmoe'
TIGERVNC_VIEWER_WIN10='/mnt/c/Users/Public/Downloads/tigervnc/vncviewer64.exe'
TIGERVNC_BIN='/usr/bin/tigervncserver'
KDE_PLASMA_WAYLAND=false
unset TMOE_WSL
########################
check_tmoe_locale() {
    if [ -e "${TMOE_LOCALE_FILE}" ]; then
        TMOE_LANG=$(head -n 1 ${TMOE_LOCALE_FILE})
    else
        TMOE_LANG="zh_CN.UTF-8"
    fi
    export LANG="${TMOE_LANG}"
}
###########
check_current_user_name_and_group() {
    CURRENT_USER_NAME=$(grep "${HOME}" /etc/passwd | awk -F ':' '{print $1}' | head -n 1)
    CURRENT_USER_GROUP=$(grep "${HOME}" /etc/passwd | awk -F ':' '{print $4}' | cut -d ',' -f 1 | head -n 1)
    if [ -z "${CURRENT_USER_GROUP}" ]; then
        CURRENT_USER_GROUP=${CURRENT_USER_NAME}
    fi
}
###############
fix_vnc_permissions() {
    check_current_user_name_and_group
    CURRENT_USER_VNC_FILE_PERMISSION=$(ls -l ${TMOE_VNC_PASSWD_FILE} | awk -F ' ' '{print $3}')
    case ${CURRENT_USER_VNC_FILE_PERMISSION} in
    ${CURRENT_USER_NAME}) ;;
    *)
        #printf "%s\n" "检测到${TMOE_VNC_PASSWD_FILE}文件所属非当前用户（${CURRENT_USER_NAME}），为避免权限问题，正在将${HOME}目录下的.vnc 的权限归属修改为${CURRENT_USER_NAME}用户和${CURRENT_USER_GROUP}用户组"
        cd ${HOME}
        sudo -E chown -Rv ${CURRENT_USER_NAME}:${CURRENT_USER_GROUP} .vnc || su -c "chown -Rv ${CURRENT_USER_NAME}:${CURRENT_USER_GROUP} .vnc"
        for i in ".ICEauthority" ".Xauthority"; do
            if [ -e "${i}" ]; then
                sudo -E chown -Rv ${CURRENT_USER_NAME}:${CURRENT_USER_GROUP} "${i}" || su -c "chown -Rv ${CURRENT_USER_NAME}:${CURRENT_USER_GROUP} ${i}"
            fi
        done
        unset i
        ;;
    esac
}
##############
check_vnc_port() {
    #CURRENT_PORT=$(sed -n p /usr/local/bin/startvnc | grep '\-geometry' | awk -F ' ' '$0=$NF' | cut -d ':' -f 2 | tail -n 1)
    CURRENT_PORT=${TMOE_VNC_DISPLAY_NUMBER}
    CURRENT_VNC_PORT=$((${CURRENT_PORT} + 5900))
}
############
tmoe_vnc_preconfigure() {
    check_tmoe_locale
    if [[ ! -s "${TMOE_VNC_PASSWD_FILE}" ]]; then
        sudo -E cp -rvf "/root/.vnc" "${HOME}" || su -c "cp -rvf /root/.vnc ${HOME}"
        if [ ! -e "${TMOE_VNC_PASSWD_FILE}" ]; then
            cd ${TMOE_GIT_DIR}
            case $(id -u) in
            0)
                git reset --hard origin/master
                git pull --rebase --stat origin master --allow-unrelated-histories || git rebase --skip
                ./tool.sh -passwd
                ;;
            *)
                sudo git reset --hard origin/master
                sudo git pull --rebase --stat origin master --allow-unrelated-histories || sudo git rebase --skip
                sudo -E bash ./tool.sh -passwd
                ;;
            esac
        fi
    fi
    fix_vnc_permissions
    if [ "$(uname -r | cut -d '-' -f 3)" = "Microsoft" ] || [ "$(uname -r | cut -d '-' -f 2)" = "microsoft" ]; then
        export TMOE_CHROOT='true'
        export TMOE_WSL='true'
        . ${TMOE_LINUX_DIR}/wsl_pulse_audio
    fi
}
###############
display_vnc_ip_addr() {
    check_vnc_port
    TMOE_IP_ADDR=$(ip -4 -br -c a | awk '{print $NF}' | cut -d '/' -f 1 | grep -v '127\.0\.0\.1' | sed "s@\$@:${CURRENT_VNC_PORT}@")
    TMOE_IPV6_ADDR=$(ip -6 -c a | grep '/' | grep -v 'fe80::.*/64' | awk '{print $2}' | cut -d '/' -f 1 | sed "s@^@[@g;s@\$@]:${CURRENT_VNC_PORT}@g")
    case ${TMOE_LANG} in
    zh_*UTF-8)
        cat <<-EOF
正在启动vnc服务,${YELLOW}本机${RESET}vnc地址 ${BLUE}localhost${GREEN}:${CURRENT_VNC_PORT}${RESET}
${YELLOW}IPv6${RESET}地址 ${TMOE_IPV6_ADDR}
The LAN VNC address ${YELLOW}局域网${RESET}地址 ${TMOE_IP_ADDR}
EOF
        ;;
    *)
        cat <<-EOF
The ${YELLOW}local${RESET} vnc address is ${BLUE}localhost${GREEN}:${CURRENT_VNC_PORT}${RESET}
The ${YELLOW}IPv6${YELLOW} address is ${TMOE_IPV6_ADDR}
The ${YELLOW}LAN${RESET} vnc address is ${TMOE_IP_ADDR}
EOF
        ;;
    esac

}
############
start_win10_tigervnc() {
    case ${TMOE_WSL} in
    true)
        cd ${HOME} || cd /tmp
        nohup ${TIGERVNC_VIEWER_WIN10} -PasswordFile ${TMOE_VNC_PASSWD_FILE} localhost:${CURRENT_VNC_PORT} &>/dev/null &
        cd - &>/dev/null
        ;;
    esac
}
##########
start_tmoe_xvnc() {
    case ${VNC_SERVER} in
    tight* | Tight*)
        XVNC_BIN='Xtightvnc'
        TMOE_VNC_BIN='tight'
        if [[ ! $(command -v ${XVNC_BIN}) ]]; then
            printf "%s\n" "${PURPLE}sudo ${GREEN}apt ${YELLOW}install ${BLUE}tightvncserver${RESET}"
            sudo apt install tightvncserver || su -c "apt install -y tightvncserver"
        fi
        ;;
    tiger* | Tiger* | *)
        XVNC_BIN='Xtigervnc'
        TMOE_VNC_BIN='tiger'
        #if [[ ! $(command -v ${XVNC_BIN}) ]]; then
        #    printf "%s\n" "${PURPLE}sudo ${GREEN}apt ${YELLOW}install ${BLUE}tigervnc-standalone-server tigervnc-common${RESET}"
        #    sudo apt install tigervnc-standalone-server tigervnc-common || su -c "apt install -y tigervnc-standalone-server"
        [[ $(command -v ${XVNC_BIN}) ]] || XVNC_BIN='Xvnc'
        # fi
        ;;
    esac
    . ${TIGERVNC_CONFIG_FILE} 2>/dev/null

    if [[ ! ${ZLIB_LEVEL} =~ ^[0-9]+$ ]]; then
        ZLIB_LEVEL=0
    elif ((${ZLIB_LEVEL} >= 10)); then
        ZLIB_LEVEL=9
    fi
    if [[ ! ${PIXEL_DEPTH} =~ ^[0-9]+$ ]]; then
        ZLIB_LEVEL=24
    elif ((${PIXEL_DEPTH} > 32)); then
        PIXEL_DEPTH=32
    fi
    #[[ $(readlink /etc/alternatives/vncserver) = "${TIGERVNC_BIN}" || $(command -v vncsession) ]]
    if [[ ${TMOE_VNC_BIN} = tiger ]]; then
        set -- "${@}" "-ZlibLevel=${ZLIB_LEVEL}"
        set -- "${@}" "-rfbwait" "30000"
        set -- "${@}" "-pn"
    fi
    if [[ ${VNC_LOCALHOST} = true ]]; then
        set -- "${@}" "-localhost"
    fi
    if [[ ${X509_VNC_ENABLED} = true && -e ${X509_KEY} && -e ${X509_CERTIFICATE} ]]; then
        set -- "${@}" "-SecurityTypes" "X509Vnc,X509Plain,X509None,VncAuth,TLSVnc"
        set -- "${@}" "-X509Key" "${X509_KEY}"
        set -- "${@}" "-X509Cert" "${X509_CERTIFICATE}"
    fi
    if [[ ${ALWAYS_SHARED} = true ]]; then
        set -- "${@}" "-alwaysshared"
    fi
    set -- "${@}" "-a" "5"
    set -- "${@}" "-wm"
    set -- "${@}" "-geometry" "${VNC_RESOLUTION}"
    set -- "${@}" "-once"
    set -- "${@}" "-depth" "${PIXEL_DEPTH}"
    #set -- "${@}" "-deferglyphs" "16"
    set -- "${@}" "-rfbauth" "${TMOE_VNC_PASSWD_FILE}"
    set -- "${@}" "-desktop" "${desktop}"
    set -- "${@}" ":${TMOE_VNC_DISPLAY_NUMBER}"
    set -- "${XVNC_BIN}" "${@}"
    if [[ ${VNC_USER} = $(whoami) || -z ${VNC_USER} ]]; then
        "${@}" &
    else
        #XVNC_COMMAND="${@}"
        #sudo su - ${VNC_USER} -c "${XVNC_COMMAND} &" || su - ${VNC_USER} -c "${XVNC_COMMAND} &"
        sudo su - ${VNC_USER} -c '"$0" "$@" &' -- "$@" || su - ${VNC_USER} -c '"$0" "$@" &' -- "$@"
    fi
    export DISPLAY=:${TMOE_VNC_DISPLAY_NUMBER}
    if [[ KDE_PLASMA_WAYLAND = true && $(command -v startplasma-wayland) ]]; then
        konsole &>/dev/null &
        startplasma-wayland &
    else
        if [[ ${VNC_USER} = $(whoami) || -z ${VNC_USER} ]]; then
            . ${XSESSION_FILE} &>/dev/null &
        else
            # if [[ ${VNC_USER} != root ]]; then
            #     sudo -E su ${VNC_USER} -c "export PATH=$(printf '%s\n' "${PATH}" | sed 's@:/usr/local/sbin:@:@;s@:/usr/sbin:@:@;s@:/sbin:@:@;s@/root/.zinit/polaris/bin:@@');source ${XSESSION_FILE} &"
            #su - (X)
            #preserve environment in container
            #else
            #    sudo -E su ${VNC_USER} -c "source ${XSESSION_FILE} &" || su ${VNC_USER} -c "source ${XSESSION_FILE} &"
            #fi
            sudo su - ${VNC_USER} -c "export LANG=${LANG};export PULSE_SERVER=${PULSE_SERVER};export TMOE_CHROOT=${TMOE_CHROOT};export TMOE_PROOT=${TMOE_PROOT};export DISPLAY=${DISPLAY};bash ${XSESSION_FILE} &" || su - ${VNC_USER} -c "export LANG=${LANG};export PULSE_SERVER=${PULSE_SERVER};export TMOE_CHROOT=${TMOE_CHROOT};export TMOE_PROOT=${TMOE_PROOT};export DISPLAY=${DISPLAY};bash ${XSESSION_FILE} &"
        fi
    fi
    start_win10_tigervnc
    exit 0
}
##############
source_tmoe_dbus_daemon() {
    [[ ${DBUS_ENABLED} != true ]] || source ${TMOE_TOOL_DIR}/gui/launch_dbus_daemon
}
###########
check_vncsession() {
    if [ $(command -v vncsession) ]; then
        case $(id -u) in
        0)
            vncsession $(whoami) :${TMOE_VNC_DISPLAY_NUMBER}
            start_win10_tigervnc
            exit 0
            ;;
        *) check_xvnc ;;
        esac
    else
        check_xvnc
    fi
}
#########
check_xvnc() {
    if [ $(command -v Xvnc) ]; then
        start_tmoe_xvnc
        exit 0
    fi
}
##########
tmoe_vnc_preconfigure
source_tmoe_dbus_daemon
display_vnc_ip_addr
#check_vncsession
check_xvnc
##########
[[ $(command -v vncserver) ]] || startx11vnc
#最后一行命令已废弃，仅作兼容性测试，直接修改其参数值可能不会生效。
#20200912注:tigervnc-1.11.0-2及其之后的版本，可能无法使用旧版命令。
vncserver -geometry 1440x720 -depth 24 -name tmoe-linux :1
